package com.lib76.DBInfo.dao;

import java.sql.SQLClientInfoException;
import java.util.List;
import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lib76.DBInfo.model.po.mysql.Database;
import com.lib76.DBInfo.model.po.mysql.DatabaseTable;
import com.lib76.DBInfo.model.po.mysql.TableColumn;
import com.lib76.DBInfo.service.DatabaseTypeEnum;
import com.lib76.DBInfo.service.IDatabaseInfoDao;
import com.lib76.DBInfo.service.JPALinkServer;

/**
 * MYSQL数据库信息访问
 * @author 张浩
 * @version 0.0.1
 */
public class MysqlInfoDao implements IDatabaseInfoDao{

	static Logger logger = LoggerFactory.getLogger(MysqlInfoDao.class);
	
	public final static String DATABASE_NAME = "information_schema";
	
	EntityManager entityManager;
	
	public MysqlInfoDao(String ip,Integer port,String userName,String userPwd) throws SQLClientInfoException{
		Properties properties = JPALinkServer.getProperties(DatabaseTypeEnum.MYSQL, ip, port, userName, userPwd, DATABASE_NAME);
		this.entityManager = JPALinkServer.getEntityManager(DatabaseTypeEnum.MYSQL, properties);
	
	}
	
	/**
	 * 获取所有数据库
	 * @return
	 */
	public List<Database> findAllDatabase(){
		Query query = entityManager.createQuery("select t from Database as t");
		return query.getResultList();
	}
	
	/**
	 * 查找数据库所有表
	 * @param databaseName	数据库名称
	 * @return
	 */
	public List<DatabaseTable> findAllTable(String databaseName){
		Query query = entityManager.createQuery("select t from DatabaseTable as t where t.id.tableSchema = ?1");
		query.setParameter(1, databaseName);
		return query.getResultList();
	}
	 
	/**
	 * 查找数据库表所有字段
	 * @param databaseName	数据库名称
	 * @param tableName		表名称
	 * @return
	 */
	public List<TableColumn> findAllColumn(String databaseName,String tableName){
		Query query = entityManager.createQuery("select t from TableColumn as t where t.id.tableSchema = ?1 and t.id.tableName = ?2");
		query.setParameter(1, databaseName);
		query.setParameter(2, tableName);
		return query.getResultList();
	}
	
	/**
	 * 将MYSQL数据类型转换成JAVA数据类型
	 * @param dbType MYSQL数据类型
	 * @return
	 */
	public static String mySqlDbType2JavaType(String dbType){
		if("bigint".equals(dbType)){
			return "Long";
		}else if("int".equals(dbType) || "integer".equals(dbType) || "tinyint".equals(dbType)){
			return "Integer";
		}else if("double".equals(dbType)){
			return "Double";
		}else if("float".equals(dbType)){
			return "Float";
		}else if("datetime".equals(dbType) || "date".equals(dbType)){
			return "Date";
		}
		return "String";
	}
}
